package git.soulbgm.restapi.amap.com;

import git.soulbgm.stats.gov.cn.AdministrativeDivision;
import git.soulbgm.stats.gov.cn.StatsApplication;
import git.soulbgm.utils.IoUtil;
import git.soulbgm.utils.JsonUtil;
import git.soulbgm.utils.LogUtil;
import git.soulbgm.utils.StringUtil;
import git.soulbgm.utils.okhttp.OkHttpUtil;

import java.util.Arrays;
import java.util.List;

/**
 * 获取国家统计局行政区划的边界坐标数据应用程序
 *
 * @author SoulBGM
 * @date 2022/10/17 17:53
 */
public class AmapApplication {

    private static final LogUtil LOG = new LogUtil(AmapApplication.class);
    private static final String MAP_KEY = "";
    private static final String MAP_API_PATH = "https://restapi.amap.com/v3/config/district?keywords={}&subdistrict=0&extensions=all&key=" + MAP_KEY;
    private static final String STORAGE_BOUNDARY_COORDINATE_POINT_BASE_PATH = "D:/行政区划边界坐标/";

    private static final List<String> FILTER_NAME_LIST = Arrays.asList("省直辖县级行政区划");

    public static void main(String[] args) throws Exception {
        List<AdministrativeDivision> adList = StatsApplication.getAdministrativeDivisions();

        for (int i = 0; i < adList.size(); i++) {
            AdministrativeDivision a = adList.get(i);
            String name = a.name;
            String basePath = STORAGE_BOUNDARY_COORDINATE_POINT_BASE_PATH + name + "/";
            LOG.info("开始获取{}的边界坐标", name);
            IoUtil.writer(basePath + a.code + ".txt", getPolyline(name));
            List<AdministrativeDivision> child = a.child;
            if (child.size() <= 1) {
                continue;
            }
            for (AdministrativeDivision c : child) {
                String childName = c.name;
                if (FILTER_NAME_LIST.contains(childName)) {
                    continue;
                }
                LOG.info("开始获取{}-{}的边界坐标", name, childName);
                try {
                    IoUtil.writer(basePath + c.code + ".txt", getPolyline(childName));
                } catch (Exception e) {
                    LOG.error("获取边界坐标失败", e);
                }
            }
        }
    }

    /**
     * 得到的行政区划边界坐标
     *
     * @param name 省市区的名称
     * @return {@link String}
     */
    private static String getPolyline(String name) {
        String url = StringUtil.format(MAP_API_PATH, name);
        String json = OkHttpUtil.get(url);
        MapInfo info = JsonUtil.parse(json, MapInfo.class);
        assert info != null;
        return info.getDistricts().get(0).getPolyline();
    }

}
